import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import Validation from 'backbone-validation';

import { formatAmount } from '../../../math.js';
import { formatDate } from '../../../date.js';

const PaymentLineView = Mn.View.extend({
    tagName: 'tr',
    className: 'row taskline',
    template: require('./templates/PaymentLineView.mustache'),
    modelEvents: {
        'change': 'render',
    },
    ui:{
        up_button: 'button.up',
        down_button: 'button.down',
        edit_button: 'button.edit',
        delete_button: 'button.delete'
    },
    triggers: {
        'click @ui.up_button': 'order:up',
        'click @ui.down_button': 'order:down',
        'click @ui.edit_button': 'edit',
        'click @ui.delete_button': 'delete'
    },
    initialize: function(options){
        var channel = Radio.channel('facade');
        this.listenTo(channel, 'bind:validation', this.bindValidation);
        this.listenTo(channel, 'unbind:validation', this.unbindValidation);
        this.listenTo(this.model, 'validated:invalid', this.showErrors);
        this.listenTo(this.model, 'validated:valid', this.hideErrors.bind(this));
    },
    showErrors(model, errors){
        this.$el.addClass('error');
    },
    hideErrors(model){
        this.$el.removeClass('error');
    },
    bindValidation(){
        Validation.bind(this);
    },
    unbindValidation(){
        Validation.unbind(this);
    },
    templateContext: function(){
        let min_order = this.model.collection.getMinOrder();
        let max_order = this.model.collection.getMaxOrder();
        let order = this.model.get('order');
        return {
            edit: this.getOption('edit'),
            show_date: this.getOption('show_date'),
            date: formatDate(this.model.get('date')),
            amount: formatAmount(this.model.get('amount')),
            is_not_first: order != min_order,
            is_not_before_last: order != max_order - 1,
            is_not_last: order != max_order
        }
    }
});
export default PaymentLineView;
